//
//  PainterTJ.m
//  ChartRefactor
//
//  Created by CaoJun on 15/3/16.
//  Copyright (c) 2015年 CaoJun. All rights reserved.
//

#import "PainterIndexTJ.h"

using namespace std;
using namespace ytx;

@implementation PainterIndexTJ

- (void)drawRect:(CGRect)cgrect withContext:(ChartCanvas *) ctx withViewModelIndexPosition:(ViewModelIndexPosition *) indexPosition
{
    KLineData * data = (KLineData *)indexPosition->getData();
    
    YTXConfig * config = YTXConfig::getInstance();
    ytx::Style style = config->style;
    Rectangle & rect = indexPosition->getRectangle();
    
    float zoomX = rect.getZoomX(), x = rect.getBeginX() + zoomX * 0.5;
    
    vector<std::vector<double> > & lineData = data->getLineData();
    
    if (lineData.size() < 1 && lineData[0].size() < 1) {
        return;
    }
    
    std::vector<KLineItem> & kLineItems =  data->getKLineData();
    
    int startIndex = indexPosition->getStartDataIndex(), endIndex = indexPosition->getEndDataIndex();
    
    double top = lineData[1][data->getDataLength()-1];
    double bottom = lineData[3][data->getDataLength()-1];
    double close = kLineItems.back().close;
    
    std::vector<double>ployData1, ployData2;
    string tjcolor = style.TJFillColorTop;
    
    if( close >= top ){
        ployData1 = lineData[0];
        ployData2 = lineData[1];
        tjcolor = style.TJFillColorTop;
    }
    else if ( close <= bottom ) {
        ployData1 = lineData[3];
        ployData2 = lineData[4];
        tjcolor = style.TJFillColorBottom;
    }
    else{
        return;
        //if ( close < top && close > bottom){
        //ployData1 = lineData[1];
        //ployData2 = lineData[3];
//        tjcolor  = style.TJFillColorTop;
    }
    
    if (ployData1.size() < 2 || ployData2.size() < 2) {
        return;
    }
    
    NSMutableArray * path = [NSMutableArray array];
    
    for(int i = startIndex; i< endIndex; i++){
        if(!isnan(ployData1[i])){
            [path addObject:[NSValue valueWithCGPoint:CGPointMake(x,rect.getPxY(ployData1[i]))]];
        }
        x += zoomX;
    }
    
    x -= zoomX;
    
    for(int i = endIndex-1; i>= startIndex; i--){
        if(!isnan(ployData2[i])){
            [path addObject:[NSValue valueWithCGPoint:CGPointMake(x,rect.getPxY(ployData2[i]))]];
        }
        x -= zoomX;
    }
    
    [ctx fillPath:[NSArray arrayWithArray:path] withFillColor:[NSString stringWithUTF8String:tjcolor.c_str()]];
    
    
}


@end
